//
//  QJPointPayVC.m
//  QuanJieShopProject
//
//  Created by SunChao on 2018/6/8.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QJPointPayVC.h"

//支付宝SDK
#import <AlipaySDK/AlipaySDK.h>
//微信
#import "WXApiManager.h"
#import "PayMethodView.h"
@interface QJPointPayVC () <WXApiManagerDelegate>

@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong)UITableView *tbView;
@property (nonatomic,assign)BOOL silverShow;//银元宝
@property (nonatomic,assign)BOOL pointShow;//积分
@property (nonatomic,assign)BOOL isSilverEnough;//余额是否足够
@property (nonatomic,assign)BOOL isPointEnough;//积分是否足够
@property (nonatomic,strong)PayMethodView *payView;
@end

@implementation QJPointPayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"支付";
    //支付宝支付成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayGengXingData) name:@"alipaysuccsed" object:nil];
    //支付宝支付失败通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayErrorAction) name:@"alipayerror" object:nil];
    //微信支付
    [WXApiManager sharedManager].delegate = self;
    
     [self createUI];
}


- (void)createUI{
    
    
    float  total = [self.totalAmountStr floatValue];
    float points = [self.pointsAmount floatValue];//积分
    if (points>=total) {
        self.isPointEnough = YES;
    }else{
        self.isPointEnough = NO;
    }
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, 150, 20)];
    label.text = @"请选择支付方式";
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor lightGrayColor];
    [self.view addSubview:label];
    
    
    UILabel *moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(UISCREEN_WIDTH- 150, 20, 150, 20)];
    moneyLabel.text = [NSString stringWithFormat:@"总金额 %@ 元",self.totalAmountStr];
    moneyLabel.textColor = [UIColor redColor];
    moneyLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:moneyLabel];
    
    
    
    
    float y  = CGRectGetMaxY(label.frame)+50;
    
    
    self.payView = [[PayMethodView alloc]init];
    self.payView.frame = CGRectMake(0, y, UISCREEN_WIDTH, 50);
    self.pointBtn = self.payView.selBtn;
    [self.pointBtn addTarget:self action:@selector(payMethodAcion:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.payView];
    
    [self.payView setViewWithImage:@"Hyuepay" title:@"会员积分" score:self.pointsAmount];
    self.pointBtn.tag = 100;
    
        self.payView = [[PayMethodView alloc]init];
        self.payView.frame = CGRectMake(0, y+50, UISCREEN_WIDTH, 50);
        self.silverBtn = self.payView.selBtn;
        [self.silverBtn addTarget:self action:@selector(payMethodAcion:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.payView];
    
    [self.payView setViewWithImage:@"Hyuepay" title:@"银元宝积分" score:self.silverAmount];
        self.silverBtn.tag = 200;
   
    self.payView = [[PayMethodView alloc]init];
    self.payView.frame = CGRectMake(0, y+100, UISCREEN_WIDTH, 50);
    self.apayBtn = self.payView.selBtn;
    [self.apayBtn addTarget:self action:@selector(payMethodAcion:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.payView];
    [self.payView setViewWithImage:@"Hali" title:@"支付宝" score:@""];
    self.apayBtn.tag = 300;
    
    self.payView = [[PayMethodView alloc]init];
    self.payView.frame = CGRectMake(0, y+150, UISCREEN_WIDTH, 50);
    self.wxBtn = self.payView.selBtn;
    [self.wxBtn addTarget:self action:@selector(payMethodAcion:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.payView];
    [self.payView setViewWithImage:@"Hwx" title:@"微信" score:@""];
    self.wxBtn.tag = 400;
    
    UIButton *submitBtn = [UIButton buttonWithType:0];
    submitBtn.frame = CGRectMake(20, y+200+100, UISCREEN_WIDTH-40, 40);
    [submitBtn setBackgroundColor:[UIColor redColor]];
    [submitBtn setTitle:@"立即支付" forState:UIControlStateNormal];
    [submitBtn setTintColor:[UIColor whiteColor]];
    [submitBtn addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:submitBtn];
    
    UILabel *tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, y+350, UISCREEN_WIDTH-40, 100)];
    [self.view addSubview:tipLabel];
    tipLabel.numberOfLines = 0;
    tipLabel.text =@"温馨提示:可使用会员积分单独支付,会员积分不足时可使用会员积分+银元宝积分混合支付,如仍小于总金额则只能使用微信或支付宝支付.";
    tipLabel.textColor = [UIColor redColor];
    tipLabel.font = [UIFont systemFontOfSize:15];
}
- (void)payMethodAcion:(UIButton *)button{
    
    button.selected = !button.selected;
    
    
    if (button.tag == 100) {//积分
        self.apayBtn.selected = NO;
        self.wxBtn.selected = NO;
    }
    
    if (button.tag == 200) {//银元宝

        if (self.isPointEnough == YES) {
            
            self.silverBtn.selected = NO;
            [MBPHUD showAlertWithTitle:@"请优先使用积分支付"];
            return;
        }
        if (self.silverBtn.selected == YES) {
            [MBPHUD showAlertWithTitle:@"使用银元宝积分需优先扣除会员积分"];
        }
        self.apayBtn.selected = NO;
        self.wxBtn.selected = NO;
        self.pointBtn.selected = YES;

    }
    if (button.tag == 300) {//支付宝
        self.pointBtn.selected = NO;
        self.silverBtn.selected = NO;
        self.pointBtn.selected = NO;
        self.wxBtn.selected = NO;
        
    }
    if (button.tag == 400) {//微信
        self.pointBtn.selected = NO;
        self.silverBtn.selected = NO;
        self.apayBtn.selected = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    //控件不被导航栏遮挡
    self.navigationController.navigationBar.translucent = NO;
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //控件不被导航栏遮挡
    self.navigationController.navigationBar.translucent = YES;
}
#pragma mark -- 支付方法
- (void)payOrderActionWithPayStr:(id)payStr{
    
    if ([self.payType containsString:@"alipayapp"]) {
        
        NSString *responseStr = [NSString stringWithFormat:@"%@",payStr[@"data"]];
        //支付宝
        [[AlipaySDK defaultService] payOrder:responseStr fromScheme:MyAppScheme callback:^(NSDictionary *resultDic) {
            
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                //支付成功
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipaysuccsed" object:resultDic];
            }else{
                //支付失败
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipayerror" object:resultDic];
            }
            
        }];
    }else if ([self.payType containsString:@"appWeixinPay"]){
        //微信
        //时间戳
        //time_t now;
        //time(&now);
        //NSString *stamp  = [NSString stringWithFormat:@"%ld", now];
        if ([payStr isKindOfClass:[NSDictionary class]]) {
            PayReq *req = [[PayReq alloc]init];
            req.partnerId = [payStr objectForKey:@"partnerid"];
            req.prepayId = [payStr objectForKey:@"prepayid"];
            req.nonceStr = [payStr objectForKey:@"noncestr"];
            NSString *time = [payStr objectForKey:@"timestamp"];
            req.timeStamp = [time intValue];
            req.package = [payStr objectForKey:@"package"];
            req.sign = [payStr objectForKey:@"sign"];
            [WXApi sendReq:req];
        }
    }else{
        //余额
        [MBPHUD showAlertWithTitle:@"支付成功"];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
- (void)alipayGengXingData{
    
    [UIView animateWithDuration:3.0f animations:^{
        
        [MBPHUD showAlertWithTitle:@"支付宝支付成功!"];
        
    }completion:^(BOOL finished) {
        
        KPopViewControllerAction;
    }];
    
}
#pragma mark -- 支付宝充值失败的提示
- (void)alipayErrorAction{
    [UIView animateWithDuration:3.0f animations:^{
        
        [MBPHUD showAlertWithTitle:@"支付宝支付失败!"];
        
    }completion:^(BOOL finished) {
        
        KPopViewControllerAction;
    }];
}
#pragma mark -- 微信支付成功回调方法
- (void)managerDidPaySucced{
    
    [UIView animateWithDuration:3.0f animations:^{
        
        [MBPHUD showAlertWithTitle:@"微信支付成功!"];
        
    }completion:^(BOOL finished) {
        
        KPopViewControllerAction;
    }];
}
#pragma mark -- 微信支付失败回调方法
- (void)managerDidPayFailed{
    
    
    [UIView animateWithDuration:3.0f animations:^{
        
        [MBPHUD showAlertWithTitle:@"微信支付失败!"];
        
    }completion:^(BOOL finished) {
        
        KPopViewControllerAction;
    }];
    
    
}

- (void)submitAction:(UIButton *)button {
    
    
    double  total = [self.totalAmountStr doubleValue];
    double silver = [self.silverAmount doubleValue];//银元宝
    double points = [self.pointsAmount doubleValue];//积分
    if (self.silverBtn.selected == NO&&self.pointBtn.selected == NO&self.apayBtn.selected ==NO&self.wxBtn.selected == NO) {
        [MBPHUD showAlertWithTitle:@"请选择支付方式"];
        return;
    }
    
    
    WEAKSELF
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.payOrderStr forKey:@"order_id"];
    if (self.pointBtn.selected == YES) {
        if (self.silverBtn.selected == NO) {//只使用积分
            if (total>points) {
                [MBPHUD showAlertWithTitle:@"积分不足,可使用银元宝混合支付"];
                return;
            }else{
                
                
                
                self.payType = @"balance";
                 [dict setObject:self.totalAmountStr forKey:@"commit_pointsAmount"];//积分ok
                 [dict setObject:self.payType forKey:@"pay_code"];
            }
            
        }
    }
        if (self.silverBtn.selected == YES) {//积分银元宝混合支付
            if (total>points+silver) {
                [MBPHUD showAlertWithTitle:@"积分银元宝不足,请使用微信或支付宝支付"];
                return;
            }else{
                self.payType = @"balance";
                float silverTakeOff = total - points;
                NSString *silverTakeOffString = [NSString stringWithFormat:@"%lf",silverTakeOff];
                 [dict setObject:self.pointsAmount forKey:@"commit_pointsAmount"];//积分ok
                [dict setObject:silverTakeOffString forKey:@"commit_silver_amount"];
                 [dict setObject:self.payType forKey:@"pay_code"];
            }
        }
   
    if (self.apayBtn.selected == YES) {
        self.payType = @"alipayapp";
        [dict setObject:self.payType forKey:@"pay_code"];
        
    }
    if (self.wxBtn.selected == YES) {
        self.payType = @"appWeixinPay";
        [dict setObject:self.payType forKey:@"pay_code"];
    }
    
    
    [WWNetRequest fetchPayOrderWithParameters:dict success:^(id response) {
        if (response) {
            
            [weakSelf payOrderActionWithPayStr:response];
            
        }
        
    } failure:^(NSDictionary *error) {
        
        [MBPHUD showAlertWithTitle:error[@"msg"]];
    }];
}

@end
